package com.xxgc.demo.job;

import cn.hutool.extra.spring.SpringUtil;
import com.xxgc.demo.controller.pojo.PictureRecyclingPOJO;
import com.xxgc.demo.utils.ApplicationContextUtils;
import com.xxgc.demo.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * @Author: Sjy
 * @Date :2023/10/10 - 10 - 10 - 10:43
 * 垃圾图片回收任务
 */
@Slf4j
public class JunkImagesJob implements Job {
    //IOC是不会生效的
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //hutool工具箱获取bean
        //用户解决@Autowired  @Resource不生效时使用
        RedisUtil redisUtil = SpringUtil.getBean("redisUtil");
        //RedisUtil redisUtil = (RedisUtil) ApplicationContextUtils.getBean("redisUtil");
        int i = 0;//从第几个开始
        int j = 50;//每页多少个
        int k = j;
        while (true){
            List<Object> junk_images = redisUtil.lGet("junk_images", i, j);
            if(junk_images.size() == 0){
                log.info(i+"到"+j+"有没可清理的垃圾图片");
                break;
            }else{//还有垃圾图片
                i += k;
                j += k;
            }
            //当前时间
            LocalDateTime now = LocalDateTime.now();

            //循环垃圾图片进行时间判断
            for (Object junk_image : junk_images) {
                PictureRecyclingPOJO prPO = (PictureRecyclingPOJO) junk_image;
                //拿到图片上传时间
                LocalDateTime time = prPO.getTime();
                long diffMinutes = ChronoUnit.MINUTES.between(time, now);
                if (diffMinutes >= 1) {
                    //获取图片地址
                    new File(prPO.getPath()).delete();//删除原图
                    new File(prPO.getPath1()).delete();//标清图
                    new File(prPO.getPath2()).delete();//缩略图

                    //清除这张图的缓存
                    redisUtil.lRemove("junk_images",1,prPO);
                }
            }
        }
    }
}
